
<template>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="1100px" append-to-body>
        <el-form ref="form" :model="model" :rules="rules" inline label-width="170px" label-suffix=":" class="prod-form-class" v-loading="loading" :disabled="disabled">
            <el-form-item label="产品名称" prop="product_name">
                <el-input v-model.trim="model.product_name" placeholder="请输入产品名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="产品spu" prop="spu">
                <el-input v-model.trim="model.spu" placeholder="请输入产品spu" clearable></el-input>
            </el-form-item>
            <el-form-item label="采购类型" prop="purchase_type">
                <el-select v-model="model.purchase_type" placeholder="请选择采购类型" clearable>
                    <el-option v-for="(dict, index) in dict.purchaseLevelList" :key="index" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="尺码类型" prop="size_type">
                <el-select v-model="model.size_type" placeholder="请选择尺码类型" clearable>
                    <el-option v-for="(dict, index) in dict.sizeLevelList" :key="index" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="商品尺码" prop="size_variant">
                <el-input v-model.trim="model.size_variant" placeholder="请输入商品尺码" clearable></el-input>
            </el-form-item>
            <el-form-item label="商品颜色" prop="color_variant">
                <el-input v-model.trim="model.color_variant" placeholder="请输入商品颜色" clearable></el-input>
            </el-form-item>
            <el-form-item label="面料成分" prop="fabric_content">
                <el-input v-model.trim="model.fabric_content" placeholder="请输入面料成分" clearable></el-input>
            </el-form-item>
            <el-form-item label="在投人数" prop="invent_numbers">
                <el-input-number v-model.trim="model.invent_numbers" :controls="false" :min="0" placeholder="请输入在投人数" clearable></el-input-number>
            </el-form-item>
            <el-form-item label="运营者" prop="develper">
                <el-input v-model.trim="model.develper" placeholder="请输入运营者" clearable></el-input>
            </el-form-item>
            <el-form-item label="上架时间" prop="published_time">
                <el-date-picker v-model="model.published_time" type="date" placeholder="请选择上架时间" clearable> </el-date-picker>
            </el-form-item>
            <el-form-item label="采购成本(元)" prop="purchase_cost">
                <el-input-number v-model.trim="model.purchase_cost" :controls="false" :min="0" placeholder="请输入采购成本(元)" clearable></el-input-number>
            </el-form-item>
            <el-form-item label="月度采购成本(元)" prop="month_purchase_cost">
                <el-input-number v-model.trim="model.month_purchase_cost" :controls="false" :min="0" placeholder="请输入月度采购成本(元)" clearable></el-input-number>
            </el-form-item>
            <el-form-item label="附属采购成本(元)" prop="sub_purchase_cost">
                <el-input-number v-model.trim="model.sub_purchase_cost" :controls="false" :min="0" placeholder="请输入附属采购成本(元)" clearable></el-input-number>
            </el-form-item>
            <el-form-item label="预估单件物流费" prop="estimate_shipping_fee">
                <el-input v-model.trim="model.estimate_shipping_fee" placeholder="请输入预估单件物流费" clearable></el-input>
            </el-form-item>
            <el-form-item label="包裹重量(kg)" class="w120">
                <el-input-number v-model.trim="model.min_weight" :controls="false" :min="0" placeholder="最小重量(kg)" clearable class="w120"></el-input-number>
                <el-input-number v-model.trim="model.max_weight" :controls="false" :min="0" placeholder="最大重量(kg)" clearable class="w120"></el-input-number>
            </el-form-item>
            <el-form-item label="产品状态" prop="product_status">
                <el-radio-group v-model="model.product_status">
                  <el-radio v-for="(dict, index) in dict.productStatus" :key="index" :label="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="开发类型" prop="develop_type">
                <el-select v-model="model.develop_type" placeholder="请选择开发类型" clearable>
                    <el-option v-for="(dict, index) in dict.developTypeList" :key="index" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="分类" prop="product_type" class="full">
                <el-cascader v-model="model.product_type" :options="dict.categorizeList" separator="->" :props="{ multiple: false, placeholder: '请选择分类' }" clearable></el-cascader>
            </el-form-item>
            <el-form-item label="产品属性" prop="attr_values" class="full">
                <el-cascader
                    ref="attrCascader"
                    v-model="model.attr_values"
                    :options="dict.appendLevelList"
                    separator="->"
                    :props="{ multiple: true, placeholder: '请选择产品属性' }"
                    clearable
                    @change="changeLabel"
                ></el-cascader>
            </el-form-item>
            <el-form-item label="供应商" prop="supplyList" class="w750">
                <!-- <el-select v-model="model.supplyList" placeholder="请选择供应商" filterable :filter-method="filterSupply" clearable multiple popper-class="custom-select">
                    <el-option v-for="(dict, index) in supplyList" :key="index" :label="dict.supply_name" :value="dict.id"></el-option>
                </el-select> -->
                <SelectPage v-model="model.supplyList" placeholder="请选择供应商" :url="$api.supply.getSupplyListInfo" show_field="supply_name" query_field="supply_name" query_field2="spu" filterable :filter-method="filterSupply" clearable multiple popper-class="custom-select"></SelectPage>
            </el-form-item>
            <el-form-item label="备注" prop="remarks" class="full">
                <el-input type="textarea" v-model.trim="model.remarks" placeholder="请输入备注" :autosize="{ minRows: 3, maxRows: 6 }" clearable></el-input>
            </el-form-item>

            <el-form-item label="图片" prop="product_images" class="full">
                <ImageUploadMultiple v-model="model.product_images" :limit="5" :disabled="disabled"></ImageUploadMultiple>
                <!-- <ImageUpload v-model="model.product_images" :limit="5" /> -->
            </el-form-item>
            <el-form-item label="售卖页对应尺码" prop="product_size_images" class="full">
                <ImageUploadMultiple v-model="model.product_size_images" :limit="5" :disabled="disabled"></ImageUploadMultiple>
                <!-- <ImageUpload v-model="model.product_size_images" :limit="5" /> -->
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" v-if="!disabled">
            <el-button type="primary" :loading="save" :disabled="save" @click="submit">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { getDetail, getTreeList, getAppendLevel, getSizeLevel, getPurchaseLevel, addProduct, editProduct, getDevelopType } from '@/api/product'
import { getSupplyList,getSupplyListInfo } from '@/api/supply'
import { formatDate } from '@/utils'
import { PRODUCT_STATUS } from '../constant'
export default {
    name: 'ProductDialog',
    props: {
        value: {
            type: Boolean,
            default: false,
            required: true,
        },
        params: {
            type: Object,
            default: () => {},
        },
        type: {
            type: String,
            default: '',
        },
    },
    data() {
        return {
            loading: false,
            save: false,
            model: {
                product_name: '',
                spu: '',
                product_images: [],
                product_size_images: [],
                product_type_1: '',
                product_type_2: '',
                product_type_3: '',
                size_variant: '',
                color_variant: '',
                size_type: '',
                purchase_cost: undefined,
                month_purchase_cost: undefined,
                sub_purchase_cost: undefined,
                purchase_type: '',
                supply_name: '',
                develper: '',
                max_weight: undefined,
                min_weight: undefined,
                estimate_shipping_fee: '',
                published_time: '',
                invent_numbers: undefined,
                fabric_content: '',
                remarks: '',
                attr_values: [],
                supplyList: [],
                supply_links: '',
                product_status: 1,
            },
            rules: {},
            supplyList: [],
            dict: {
                developTypeList: [],
                categorizeList: [],
                appendLevelList: [],
                sizeLevelList: [],
                purchaseLevelList: [],
                supplyList: [],
                productStatus: PRODUCT_STATUS,
            },
            shareScope: -1,
        }
    },
    computed: {
        disabled() {
            return this.type === 'view'
        },
        title() {
            return `${this.type == 'edit' ? '编辑' : this.type == 'add' ? '新增' : '查看'}产品`
        },
        dialogVisible: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val)
            },
        },
    },
    async mounted() {
        this.loading = true
        try {
            const [categorizeData, appendLevelData, sizeLevelData, purchaseLevelData, supplyData, developTypeData] = await Promise.all([
                getTreeList(),
                getAppendLevel(),
                getSizeLevel(),
                getPurchaseLevel(),
                getSupplyListInfo(),
                getDevelopType()
            ])
            this.dict.categorizeList = categorizeData?.data ?? []
            this.dict.appendLevelList = appendLevelData?.data ?? []
            this.dict.sizeLevelList = sizeLevelData?.data ?? []
            this.dict.purchaseLevelList = purchaseLevelData?.data ?? []
            this.dict.supplyList = supplyData?.data ?? []
            this.dict.developTypeList = developTypeData?.data ?? []
            this.filterSupply()
            if (this.type === 'edit' || this.type === 'view') {
                this.getDetail()
            }
        } catch (error) {
            console.log(error)
        }
        this.loading = false
    },
    methods: {
        filterSupply(value) {
            if(!value) {
                this.supplyList = this.dict.supplyList
            }else {
                const lowerCaseValue = value.toLowerCase()
                this.supplyList = this.dict.supplyList.filter(item =>  item.supply_name.indexOf(value)!=-1 || item.spu.toLowerCase().indexOf(lowerCaseValue)!=-1 )
            }
           
        },
        changeLabel(val) {
            for (let i = 0; i < val.length; i++) {
                if (val[i][0] != this.shareScope) {
                    this.shareScope = val[i][0]
                    break
                }
            }
            const filterd = val.filter(v => v[0] === this.shareScope)
            this.model.attr_values = []
            this.model.attr_values.push(...filterd)
        },
        getDetail() {
            this.loading = true
            const params = { id: this.params.id }
            getDetail(params)
                .then(res => {
                    this.model = Object.assign({}, this.model, res.data)
                    this.model.size_type = Number(this.model.size_type)
                    this.model.product_type = [this.model.product_type_1, this.model.product_type_2, this.model.product_type_3]
                    this.model.product_images = JSON.parse(this.model.product_images || '[]')
                    this.model.product_size_images = JSON.parse(this.model.product_size_images || '[]')
                    this.model.supplyList = this.model.supply_links_ids.split(',').map(pre => parseInt(pre))
                    if (this.model?.attr_values?.length > 0) {
                        this.model.attr_values = this.model.attr_values.map(item => {
                            const currentItem = { value: item.children_id, parent_id: item.parent_id }
                            const tempItem = this.findParents(this.dict.appendLevelList, currentItem)
                            return tempItem
                        })
                    }
                })
                .finally(() => {
                    this.loading = false
                })
        },
        findParents(list, item) {
            let parentValues = []
            const parentList = list
            const findParentsRecursive = (list, item, parents) => {
                for (let i = 0; i < list.length; i++) {
                    const current = list[i]

                    if (current.value === item.parent_id) {
                        parents.push(current.value)

                        if (current.parent_id !== '0') {
                            findParentsRecursive(parentList, current, parents)
                        }
                        break
                    } else {
                        if (parents.length == 0 && current.children) {
                            findParentsRecursive(current.children, item, parents)
                        }
                    }
                }
            }

            findParentsRecursive(list, item, parentValues)

            parentValues.reverse().push(item.value)

            return parentValues
        },
        submit() {
            const attrList = this.$refs.attrCascader.getCheckedNodes(true)

            const attr_values = attrList.map(item => {
                return {
                    parent_id: item.data.parent_id,
                    children_id: item.data.value,
                }
            })
            const params = {
                ...this.model,
                product_images: Array.isArray(this.model.product_images) ? this.model.product_images : this.model.product_images?.split(',') ?? [],
                product_size_images: Array.isArray(this.model.product_size_images) ? this.model.product_size_images : this.model?.product_size_images?.split(',') ?? [],
                product_type_1: this.model.product_type?.[0] ?? '',
                product_type_2: this.model.product_type?.[1] ?? '',
                product_type_3: this.model.product_type?.[2] ?? '',
                attr_values: attr_values,
                published_time: formatDate(this.model.published_time),
                supply_links: this.model.supplyList.join(','),
                remark: this.model.remarks,
            }
            if (this.save) {
                return
            }
            this.save = true
            if (this.type === 'edit') {
                params.id = this.params.id
                editProduct(params)
                    .then(res => {
                        this.$message.success(res.msg)
                        this.dialogVisible = false
                        this.$emit('success')
                    })
                    .finally(() => {
                        this.save = false
                    })
            } else {
                addProduct(params)
                    .then(res => {
                        this.$message.success(res.msg)
                        this.dialogVisible = false
                        this.$emit('success')
                    })
                    .finally(() => {
                        this.save = false
                    })
            }
        },
        cancel() {
            this.dialogVisible = false
        },
    },
}
</script>

<style>
.prod-form-class.el-form .el-form-item {
    width: 50%;
    margin-right: 0;
}
.prod-form-class.el-form .el-form-item .el-input {
    width: 250px;
}
.prod-form-class.el-form .el-form-item.w750 {
    width: 100%;
}
.prod-form-class.el-form .el-form-item.w750 .el-input {
    width: 770px;
}
.prod-form-class.el-form .el-form-item .el-textarea {
    width: 770px;
}
.prod-form-class.el-form .el-form-item.full {
    width: 100%;
}
.prod-form-class.el-form .el-form-item.full .el-input,
.prod-form-class.el-form .el-form-item.full .el-cascader {
    width: 770px;
}
.prod-form-class.el-form .el-form-item.w120 .el-input-number.w120 + .el-input-number {
    margin-left: 10px;
}
.prod-form-class.el-form .el-form-item .el-input-number,
.prod-form-class.el-form .el-form-item .el-input-number .el-input {
    width: 250px;
}
.prod-form-class.el-form .el-form-item.w120 .el-input-number.w120,
.prod-form-class.el-form .el-form-item.w120 .el-input-number.w120 .el-input {
    width: 120px;
}
.prod-form-class.el-form .el-input-number.is-without-controls .el-input__inner {
    text-align: left;
}
.custom-select .el-select-dropdown__item {
    max-width: 450px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>
